home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 6283 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.5 KB

  1. Path: isonews.bbn.hp.com!hpbblb!news
  2. From: Matthias Dittrich <matti>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: How do I round and truncate floats to integers?
  5. Date: 21 Feb 1996 09:47:27 GMT
  6. Organization: Hewlett-Packard Co.
  7. Message-ID: <4gepnf$jse@hpbblb.bbn.hp.com>
  8. References: <4g009b$c2n@news.tuwien.ac.at>
  9. NNTP-Posting-Host: trabant.bbn.hp.com
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 1.1N (X11; I; HP-UX A.09.07 9000/712)
  14. X-URL: news:4g009b$c2n@news.tuwien.ac.at
  15.  
  16. sor@rs6.iaee.tuwien.ac.at (Evgeni Sorokin) wrote:
  17. >Hello!
  18. >
  19. >I am myself ashamed of posting such stupid questions, but FAQ's and
  20. >books that I've found assume this to be too evident.
  21. >
  22. >Given a float (double, to be exact) how do I 
  23. >
  24. >1) round it to nearest integer (forget 0.5 problem for the moment) and
  25. >2) truncate it to the integer?
  26. >
  27. >I browsed include directories of my compilers (Turbo C and GNU) and
  28. >have not found passing functions taking floats and returning
  29. >integers. If typecasting is supposed to do the trick, then how do I
  30. >distinguish cases 1) and 2)?
  31. >...
  32. A typecast to integer truncates your floating number, this is not a trick.
  33. Negative numbers are truncated in the same way, that means -2.7 assigned to
  34. an integer gives 2 as result. I'm not sure here if this is defined behaviour
  35. or compiler dependent.
  36. To round you must distinguish these two cases. Add 0.5 to a positive floating
  37. number and subtract 0.5 from a negative one before truncating it.
  38.  
  39. Good luck,
  40. Matthias
  41.  
  42.